<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>截屏</title>
</head>
<body>
<button id="button">截屏</button>
<img id="imgBox" />

<script>
  // 总体思路，获取屏幕流，将流赋给video 标签, 使用canvas 绘制video 元素的每一帧，利用canvas 将图片转成base64 格式赋给img 标签
  var imgBox = document.getElementById('imgBox')
  // 添加截屏功能
  document.getElementById('button').onclick = function() {
    // 获取屏幕流
    navigator.mediaDevices.getDisplayMedia({
      video: true,
      audio: false
    }).then(function(stream) {
      // 创建视频元素
      var video = document.createElement('video');
      video.srcObject = stream;

      // 等待视频加载
      video.play().then(function() {
        // 将视频转换为 canvas 元素
        var canvas = document.createElement('canvas');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        var ctx = canvas.getContext('2d');
        ctx.drawImage(video, 0, 0);

        // 获取 canvas 元素的DataURL
        var dataURL = canvas.toDataURL('image/jpeg', 0.9);

        // 保存DataURL
        // ...
        imgBox.src = dataURL
        // 停止视频流
        stream.getTracks().forEach(function(track) {
          track.stop();
        });
      });
    });
  };
</script>
</body>
</html>
